package com.feiyisys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feiyisys.common.PageResult;
import com.feiyisys.common.Result;
import com.feiyisys.entity.CulturalHeritage;
import com.feiyisys.service.CulturalHeritageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 文化遗产信息表 前端控制器
 * </p>
 *
 * @author wq
 * @since 2025-10-10
 */
@RestController
@RequestMapping("/heritage")
public class CulturalHeritageController {

    @Autowired
    private CulturalHeritageService culturalHeritageService;

    /**
     * 分页查询所有文化遗产
     */
    @GetMapping
    public Result<IPage<CulturalHeritage>> getPage(@RequestParam(defaultValue = "1") Long current,
                                                   @RequestParam(defaultValue = "10") Long size) {
        Page<CulturalHeritage> page = new Page<>(current, size);
        IPage<CulturalHeritage> result = culturalHeritageService.page(page);
        return Result.success(result);
    }

    /**
     * 根据 ID 查询文化遗产
     */
    @GetMapping("/{id}")
    public Result<CulturalHeritage> getHeritageById(@PathVariable Long id) {
        CulturalHeritage heritage = culturalHeritageService.getById(id);
        return Result.success(heritage);
    }

    /**
     * 综合查询文化遗产（支持分类ID和名称模糊查询）
     */
    @GetMapping("/search")
    public Result<IPage<CulturalHeritage>> searchHeritage(
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {

        Page<CulturalHeritage> page = new Page<>(current, size);
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CulturalHeritage> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();

        // 如果提供了分类ID，则按分类ID查询
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }

        // 如果提供了名称，则按名称模糊查询
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("name", name);
        }

        // 如果两个条件都提供了，则同时应用
        IPage<CulturalHeritage> result = culturalHeritageService.page(page, queryWrapper);
        return Result.success(result); // 修改为返回 Result<IPage<CulturalHeritage>>
    }


    /**
     * 新增文化遗产
     */
    @PostMapping
    public Result<CulturalHeritage> createHeritage(@RequestBody CulturalHeritage heritage) {
        // 初始化计数器
        heritage.setViewCount(heritage.getViewCount() == null ? 0 : heritage.getViewCount());
        heritage.setLikeCount(heritage.getLikeCount() == null ? 0 : heritage.getLikeCount());
        heritage.setCollectCount(heritage.getCollectCount() == null ? 0 : heritage.getCollectCount());

        boolean saved = culturalHeritageService.save(heritage);
        if (saved) {
            return Result.success(heritage);
        } else {
            return Result.fail("文化遗产新增失败");
        }
    }
    /**
     * 增加文化遗产浏览次数（用户浏览时调用）
     */
    @PutMapping("/view/{id}")
    public Result<Boolean> increaseViewCount(@PathVariable Long id) {
        CulturalHeritage heritage = culturalHeritageService.getById(id);
        if (heritage != null) {
            // 增加浏览次数
            heritage.setViewCount(heritage.getViewCount() + 1);
            boolean updated = culturalHeritageService.updateById(heritage);
            return Result.success(updated);
        } else {
            return Result.fail("未找到指定的文化遗产");
        }
    }
    /**
     * 点赞文化遗产
     */
    @PutMapping("/like/{id}")
    public Result<Boolean> likeHeritage(@PathVariable Long id) {
        CulturalHeritage heritage = culturalHeritageService.getById(id);
        if (heritage != null) {
            // 增加点赞次数
            heritage.setLikeCount(heritage.getLikeCount() + 1);
            boolean updated = culturalHeritageService.updateById(heritage);
            if (updated) {
                return Result.success(updated);
            } else {
                return Result.fail("点赞失败");
            }
        } else {
            return Result.fail("未找到指定的文化遗产");
        }
    }

    /**
     * 取消点赞文化遗产
     */
    @PutMapping("/unlike/{id}")
    public Result<Boolean> unlikeHeritage(@PathVariable Long id) {
        CulturalHeritage heritage = culturalHeritageService.getById(id);
        if (heritage != null) {
            // 减少点赞次数，但不能小于0
            int newLikeCount = Math.max(0, heritage.getLikeCount() - 1);
            heritage.setLikeCount(newLikeCount);
            boolean updated = culturalHeritageService.updateById(heritage);
            if (updated) {
                return Result.success(updated);
            } else {
                return Result.fail("取消点赞失败");
            }
        } else {
            return Result.fail("未找到指定的文化遗产");
        }
    }
    /**
     * 收藏文化遗产
     */
    @PutMapping("/collect/{id}")
    public Result<Boolean> collectHeritage(@PathVariable Long id) {
        CulturalHeritage heritage = culturalHeritageService.getById(id);
        if (heritage != null) {
            // 增加收藏次数
            heritage.setCollectCount(heritage.getCollectCount() + 1);
            boolean updated = culturalHeritageService.updateById(heritage);
            if (updated) {
                return Result.success(updated);
            } else {
                return Result.fail("收藏失败");
            }
        } else {
            return Result.fail("未找到指定的文化遗产");
        }
    }

    /**
     * 取消收藏文化遗产
     */
    @PutMapping("/uncollect/{id}")
    public Result<Boolean> uncollectHeritage(@PathVariable Long id) {
        CulturalHeritage heritage = culturalHeritageService.getById(id);
        if (heritage != null) {
            // 减少收藏次数，但不能小于0
            int newCollectCount = Math.max(0, heritage.getCollectCount() - 1);
            heritage.setCollectCount(newCollectCount);
            boolean updated = culturalHeritageService.updateById(heritage);
            if (updated) {
                return Result.success(updated);
            } else {
                return Result.fail("取消收藏失败");
            }
        } else {
            return Result.fail("未找到指定的文化遗产");
        }
    }



    /**
     * 更新文化遗产
     */
    @PutMapping
    public Result<Boolean> updateHeritage(@RequestBody CulturalHeritage heritage) {
        boolean updated = culturalHeritageService.updateById(heritage);
        if (updated) {
            return Result.success(updated);
        } else {
            return Result.fail("文化遗产更新失败");
        }
    }

    /**
     * 删除文化遗产
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteHeritage(@PathVariable Long id) {
        boolean removed = culturalHeritageService.removeById(id);
        if (removed) {
            return Result.success(removed);
        } else {
            return Result.fail("文化遗产删除失败");
        }
    }
}